package org.itboys.shop.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.itboys.basetemplate.entity.IncomeRecord;
import org.itboys.basetemplate.service.IncomeRecordService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.CommonConstants.NUM;
import org.itboys.commons.CommonConstants.StaticParam;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ImagePathUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.member.service.MemberService;
import org.itboys.seller.constant.SellerConstants;
import org.itboys.seller.dto.SellerGetMoneyDTO;
import org.itboys.seller.entity.SellerBank;
import org.itboys.seller.entity.SellerGetMoneyRecord;
import org.itboys.seller.entity.SellerUser;
import org.itboys.seller.service.SellerBankService;
import org.itboys.seller.service.SellerGetMoneyService;
import org.itboys.seller.service.SellerUserService;
import org.itboys.shop.dto.AdminAmountRecordDto;
import org.itboys.shop.entity.ShopSeller;
import org.itboys.shop.service.ShopSellerService;
import org.itboys.shop.service.Manager.WXOrderManager;
import org.itboys.shop.tools.WXSession;
import org.itboys.trade.entity.Order;
import org.itboys.trade.entity.TicketOrder;
import org.itboys.trade.entity.mysql.AdminAmount;
import org.itboys.trade.entity.mysql.AdminAmountRecord;
import org.itboys.trade.service.OrderService;
import org.itboys.trade.service.TicketOrderService;
import org.itboys.trade.service.mysql.AdminAmountRecordService;
import org.itboys.trade.service.mysql.AdminAmountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 商品
 * 
 * @author
 *
 */
@RestController
@RequestMapping("/wx/seller")
public class WXSellerController extends BaseController {
	@Autowired
	private SellerUserService sellerUserService;
	@Autowired
	private TicketOrderService orderService;
	@Autowired
	private WXOrderManager orderManager;
	@Autowired
	private ShopSellerService shopSellerService;

	@Autowired
	private IncomeRecordService incomeRecordService;

	@Autowired
	private OrderService ordersService;

	@Autowired
	private MemberService memberService;
	@Autowired
	private AdminAmountRecordService adminAmountRecordService;
	@Autowired
	private AdminAmountService adminAmountService;


	@Autowired
	private SellerBankService sellerBankService;

	@Autowired
	private SellerGetMoneyService sellerGetMoneyService;

	@RequestMapping("/doLogin")
	public void doLogin(@RequestParam String username, @RequestParam String password, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			SellerUser proUser = sellerUserService.getAdminUser(username);
			if (proUser == null) {
				AjaxUtils.renderText(response, "用户不存在");// 用户不存在
				return;
			}
			if (!StringUtils.equals(proUser.getPassword(), Digests.md5(password))) {
				AjaxUtils.renderText(response, "密码不正确");// 密码不正确
				return;
			}
			WXSession.putSeller(request, proUser);
			AjaxUtils.renderText(response, "1");// 登入成功
		} catch (Exception e) {
			logger.info("", e);
		}

	}

	@RequestMapping("/logOut")
	public void doLogin(HttpServletRequest request, HttpServletResponse response) {

		try {
			WXSession.logOut(request);
			response.sendRedirect("http://mwx.chinatoplady.cn/weixin/login.html");
		} catch (IOException e) {
			logger.error("", e);
		}
	}

	@RequestMapping("/ticketOrderList")
	public ModelAndView ticketOrderList(@Param("status") String status, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			if (!WXSession.ifSellerLog(request)) {
				response.sendRedirect("http://mwx.chinatoplady.cn/weixin/login.html");
				return null;
			}
			SellerUser user = WXSession.getSeller(request);
			Map<String, Object> param = Maps.newHashMap();
			param.put("deleted", false);
			param.put("sellerId", user.getSellerId());
			// param.put("sellerId",sellerId);
			param.put("orderByKey", "-ut");
			if (null != status) {
				switch (status) {
				case "unreceive":
					param.put("status", TicketOrder.status_payed);
					break;
				case "success":
					param.put("status in", Lists.newArrayList(TicketOrder.status_success, TicketOrder.status_comment));
					break;
				case "other":
					param.put("status in", Lists.newArrayList(-1, -2, -3, -4));
					break;
				default:
					break;
				}

			}
			List<TicketOrder> orders = orderService.list(param);
			model.addAttribute("orders", orders.stream().map(o -> {
				return orderManager.getTicketListDto(o);
			}).collect(Collectors.toList()));
			model.addAttribute("status", status);
			return new ModelAndView("/seller/orderList");
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}

	}

	@RequestMapping("/info")
	public ModelAndView info(Model model, HttpServletRequest request, HttpServletResponse response) {
		try {
			if (!WXSession.ifSellerLog(request)) {
				response.sendRedirect("http://mwx.chinatoplady.cn/weixin/login.html");
				return null;
			}
			SellerUser user = WXSession.getSeller(request);
			ShopSeller seller = shopSellerService.getById(user.getSellerId());
			if (null == seller) {
				logger.info("seller/info 店铺不存在! sellerId=" + user.getSellerId());
				return null;
			}
			seller.setLogo(ImagePathUtils.add(StaticParam.imagePath, seller.getLogo()));
			model.addAttribute("shop", seller);
			return new ModelAndView("/seller/info");
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
	}

	@RequestMapping("/ticket")
	public ModelAndView ticket(Model model, HttpServletRequest request, HttpServletResponse response) {
		try {
			if (!WXSession.ifSellerLog(request)) {
				response.sendRedirect("http://mwx.chinatoplady.cn/weixin/login.html");
				return null;
			}
			return new ModelAndView("/seller/ticket");
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
	}

	@RequestMapping("/useTicket")
	public void useTicket(@RequestParam String code, HttpServletRequest request, HttpServletResponse response) {
		try {
			if (!WXSession.ifSellerLog(request)) {
				response.sendRedirect("http://mwx.chinatoplady.cn/weixin/login.html");
				return;
			}
			Map<String, Object> param = Maps.newHashMap();
			param.put("sellerId", WXSession.getSeller(request).getSellerId());
			param.put("code", code);
			List<TicketOrder> orders = orderService.list(param);
			if (orders.size() < 1) {
				AjaxUtils.renderText(response, "找不到该订单，请确认核销码是否有误！");
				return;
			}
			TicketOrder order = orders.get(0);
			if (order.getStatus() != TicketOrder.status_payed) {
				AjaxUtils.renderText(response, "该订单未付款或已使用！");
				return;
			}
			for (TicketOrder ticketOrder : orders) {
				ticketOrder.setStatus(TicketOrder.status_success);
				incomeRecordService.startIncomeTicket(order.getId());
				orderService.update(ticketOrder);
			}
			
			AjaxUtils.renderText(response, "1");
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	/**
	 * 商家收益
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/income")
	public ModelAndView income(HttpServletRequest request, HttpServletResponse response, Model model) {
		SellerUser seller = (SellerUser) request.getSession().getAttribute("seller");
		Double total = 0.00;//总收益
		Double wait = 0.00;// 可提现收益
		Double today = 0.00;// 今日收益
		Map<String, Object> map = new HashMap<>();
		map.put("objId", seller.getSellerId());
		List<AdminAmount> adminAmount = adminAmountService.list(map);
		for(AdminAmount amount : adminAmount){
			if(amount != null){
				 total = (amount.getTotalOrderAmount()+amount.getTotalWithdrawAmount())/100d;// 总收益
				 wait = amount.getLeftWithdrawAmount()/100d;// 可提现收益
			}
		}
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		List<AdminAmountRecord> list = adminAmountRecordService.list(map);
		List<AdminAmountRecordDto> lists = new ArrayList<AdminAmountRecordDto>();
		for (AdminAmountRecord record : list) {
			AdminAmountRecordDto recordDto = new AdminAmountRecordDto();
			String orderNo = "";
        	Member member = new Member();
        	if(record.getOrderType() == 1){
        		 Order order =  ordersService.getById(record.getOrderId());
        		 member = memberService.getById(order.getMemberId());
        		 recordDto.setNickName(member.getNickname());
        		 orderNo = order.getOrderNo();
        	}
        	if(record.getOrderType() == 2){
        		TicketOrder  torder = orderService.getById(record.getOrderId());
        		member = memberService.getById(torder.getMemberId());
        		recordDto.setNickName(member.getNickname());
        		orderNo = torder.getOrderNo();
        	}
			recordDto.setOrderNo(orderNo);
			
			if(record.getIncome() != null){
				recordDto.setMoney(record.getIncome()/100d);
			}
			Calendar c1 = Calendar.getInstance();
			c1.setTime(new Date());// 当前日期
			Calendar c2 = Calendar.getInstance();
			c2.setTime(record.getCreateTime());// 收益日期
			// 判断收益日期是否是当前日期
			if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)
					&& c1.get(Calendar.DATE) == c2.get(Calendar.DATE)) {
				if(record.getIncome()!=0){
					today += record.getIncome()/100d;
				}
			}
			recordDto.setTime(format.format(record.getCreateTime()));
			lists.add(recordDto);
		}
		model.addAttribute("totalAmount", total);
		model.addAttribute("amount", wait);
		model.addAttribute("todayAmount", today);
		model.addAttribute("recordList", lists); // 收益明细
		model.addAttribute("sellerUserId", seller.getId());

		map.clear();
		map.put("sellerId", seller.getSellerId());
		List<SellerGetMoneyRecord> list1 = sellerGetMoneyService.list(map);
		List<SellerGetMoneyDTO> dtoList = list1.stream().map(record -> {
			SellerGetMoneyDTO dto = new SellerGetMoneyDTO();
			SellerBank bank = sellerBankService.getById(record.getBankCardId());
			dto.setCardNum(bank.getCard());
			dto.setMoney(record.getMoney() / 100.0f);
			String statusStr = "";
			switch (record.getStatus()) {
			case SellerConstants.SellerGetMoneyStatus.UN_CHECK:
				statusStr = "未审核";
				break;
			case SellerConstants.SellerGetMoneyStatus.PASS:
				statusStr = "已发放";
				break;
			case SellerConstants.SellerGetMoneyStatus.REFUSE:
				statusStr = "拒绝";
				break;
			default:
				statusStr = "未知";
			}
			dto.setStatus(statusStr);
			dto.setCommitIime(TimeUtils.format(new Date(record.getCt()), CommonConstants.DATE.FORMAT_DEFAULT));
			dto.setAuditTime(TimeUtils.format(new Date(record.getUt()), CommonConstants.DATE.FORMAT_DEFAULT));
			return dto;

		}).collect(Collectors.toList());
		model.addAttribute("tixianList", dtoList);// 提现记录

		return new ModelAndView("/seller/income");
	}

	/**
	 * 跳转到提现页面
	 * 
	 * @param memberId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/towithdrawDeposit")
	public ModelAndView toWithdrawDeposit(@RequestParam Long sellerUserId, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		SellerUser seller = sellerUserService.getById(sellerUserId);
		Map<String, Object> map = new HashMap<>();
		map.put("objId", seller.getSellerId());
		Double wait = 0.00;//可提现收益
		List<AdminAmount> adminAmount = adminAmountService.list(map);
		for(AdminAmount amount : adminAmount){
			if(amount != null){
				 wait = amount.getLeftWithdrawAmount()/100d;// 可提现收益
			}
		}
		map.clear();
		map.put("sellerId", seller.getSellerId());
		map.put("isDeleted", 0);
		List<SellerBank> banklist = sellerBankService.list(map);
		if (banklist.size() > 0) {
			SellerBank bank = banklist.get(0);
			String no = bank.getCard();
			bank.setWeihao(no.substring(no.length() - 4, no.length()));
			model.addAttribute("account", bank);
		}
		model.addAttribute("amount", wait);
		model.addAttribute("sellerUserId", sellerUserId);
		return new ModelAndView("/seller/withdrawDeposit");

	}

	/**
	 * 检查是否存在未完成的申请
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/check")
	public void checkStatus(@RequestParam Long sellerUserId, HttpServletRequest request, HttpServletResponse response) {
		SellerUser seller = sellerUserService.getById(sellerUserId);
		Map<String, Object> map = new HashMap<>();
		map.put("sellerId", seller.getSellerId());
		List<SellerGetMoneyRecord> list = sellerGetMoneyService.list(map);
		for (SellerGetMoneyRecord wr : list) {
			if (wr.getStatus() == SellerConstants.SellerGetMoneyStatus.UN_CHECK) {
				AjaxUtils.renderText(response, "0");// 未审核
			}
		}
		AjaxUtils.renderText(response, "1");// 可申请提现
	}

	/**
	 * 申请提现
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("/doWithdrawDeposit")
	public void withdrawDeposit(@RequestParam Double money, @RequestParam Long sellerUserId, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		// 提现操作
	}

	/**
	 * 提现账户
	 */
	@RequestMapping("/myAccount")
	public ModelAndView myAccount(HttpServletRequest request, HttpServletResponse response, Model model) {
		SellerUser seller = (SellerUser) request.getSession().getAttribute("seller");
		Map<String, Object> param = new HashMap<>();
		param.put("sellerId", seller.getSellerId());
		param.put("isDeleted", 0);
		List<SellerBank> list = sellerBankService.list(param);
		if (list.size() > 0) {
			for (SellerBank bank : list) {
				String no = bank.getCard();
				String weihao = no.substring(no.length() - 4, no.length());
				bank.setWeihao(weihao);
			}
			model.addAttribute("accountList", list);
		}

		return new ModelAndView("/seller/sellerBank");

	}

	@RequestMapping("/toAddAccountVM")
	public ModelAndView toAddAccountVM(HttpServletRequest request, HttpServletResponse response, Model model) {
		return new ModelAndView("/seller/sellerAddBank");
	}

	/**
	 * 添加银行卡
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/addAccount")
	public void addAccount(@RequestParam String cardName, @RequestParam String cardNo, @RequestParam String bank,
			// @RequestParam String mobile,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			SellerUser seller = (SellerUser) request.getSession().getAttribute("seller");
			Long sellerId = seller.getSellerId();
			SellerBank sellerBank = new SellerBank();
			sellerBank.setSellerId(sellerId);
			sellerBank.setBankName(bank);
			sellerBank.setCard(cardNo);
			sellerBank.setUserName(cardName);
			// sellerBank.setUserPhone(mobile);
			sellerBank.setIsDeleted(0);
			sellerBankService.save(sellerBank);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("save bank info error", e);
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	@RequestMapping("/select")
	public ModelAndView select(@RequestParam Long accountId, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		SellerUser seller = (SellerUser) request.getSession().getAttribute("seller");
		SellerBank bank = sellerBankService.getById(accountId);
		String no = bank.getCard();
		if (StringUtils.isNotBlank(no)) {
			bank.setWeihao(no.substring(no.length() - 4, no.length()));
			model.addAttribute("account", bank);
		}
		Map<String,Object> map = new HashMap<>();
		map.put("objId", seller.getSellerId());
		Double wait = 0.00;
		List<AdminAmount> adminAmount = adminAmountService.list(map);
		for(AdminAmount amount : adminAmount){
			if(amount != null){
				wait = amount.getLeftWithdrawAmount()/100d;// 可提现收益
			}
		}
		model.addAttribute("amount", wait);
		model.addAttribute("sellerUserId", seller.getId());
		return new ModelAndView("/seller/withdrawDeposit");
	}

	@RequestMapping("/checkAccount")
	public void checkAccount(@RequestParam String cardNo, HttpServletRequest request, HttpServletResponse response) {
		SellerUser seller = (SellerUser) request.getSession().getAttribute("seller");
		Map<String, Object> param = new HashMap<>();
		param.put("sellerId", seller.getSellerId());
		param.put("card", cardNo);
		param.put("isDeleted", 0);
		List<SellerBank> list = sellerBankService.list(param);
		if (list.size() > 0) {
			AjaxUtils.renderText(response, "1"); // 银行卡账号已存在
		}
		AjaxUtils.renderText(response, "0");
	}

	@RequestMapping("/ticketOrderDetail")
	public ModelAndView ticketOrderDetail(@RequestParam Long orderId, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		TicketOrder order = orderService.getById(orderId);
		model.addAttribute("order", orderManager.getTicketDetailDto(order));
		return new ModelAndView("/seller/orderDetail");
	}
}
